package com.offcn.order.service.impl;

import com.offcn.dycommon.enums.OrderStatusEnumes;
import com.offcn.dycommon.enums.ProjectStatusEnume;
import com.offcn.dycommon.response.AppResponse;
import com.offcn.order.mapper.TOrderMapper;
import com.offcn.order.po.TOrder;
import com.offcn.order.service.OrderService;
import com.offcn.order.service.ProjectServiceFeign;
import com.offcn.order.vo.req.OrderInfoSubmitVo;
import com.offcn.order.vo.resp.TReturn;
import com.offcn.utils.AppDateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    //注入订单数据表操作的数据接口
    @Autowired
    private TOrderMapper orderMapper;

    //注入redis操作工具类
    @Autowired
    private StringRedisTemplate redisTemplate;

    //项目的回报信息的调用接口
    @Autowired
    private ProjectServiceFeign projectServiceFeign;


    @Override
    public TOrder saveOrder(OrderInfoSubmitVo vo) {
        //创建一个订单对象
        TOrder order = new TOrder();
        //获取请求AccessToken
        String accessToken = vo.getAccessToken();
        //根据token从redis读取用户编号
        String memberId = redisTemplate.opsForValue().get(accessToken);

        //设置用户编号到订单
        order.setMemberid(Integer.parseInt(memberId));

        //复制vo属性值到订单对象
        BeanUtils.copyProperties(vo,order);

        //生成一个订单编号
        String orderNum = UUID.randomUUID().toString().toLowerCase().replace("-", "");

        //设置订单编号
        order.setOrdernum(orderNum);

        //设置订单创建时间
        order.setCreatedate(AppDateUtils.getFormatTime());

        //使用Feign接口调用远程项目服务接口，获取指定项目的回报信息
        AppResponse<List<TReturn>> appResponse = projectServiceFeign.returnInfo(vo.getProjectid());

        //获取响应的数据
        List<TReturn> returnList = appResponse.getData();
        //读取系统默认回报信息
        if(returnList!=null&&returnList.size()>0){
            TReturn tReturn = returnList.get(0);
            System.out.println("return:"+tReturn);
            //计算项目回报金额  支持的数量*支持的金额+运费
            int totalMoney = vo.getRtncount() * tReturn.getSupportmoney() + tReturn.getFreight();
            //把项目回报金额设置到订单属性
            order.setMoney(totalMoney);




        }

        //支付的状态
        order.setStatus(OrderStatusEnumes.UNPAY.getCode()+"");
        //是否开票
        order.setInvoice(vo.getInvoice().toString());
        //保存订单数据到数据库
        orderMapper.insertSelective(order);

        return order;
    }
}
